/**
 * 
 */
package com.aboverock.common.Jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @author Rock Wang
 *
 */
public class CustomizationList {

    public static final String VERTICAL_DELIMITER = "|";

    public static class VerticalDelimiterDeserializer extends JsonDeserializer<List<String>> {
        /*
         * (non-Javadoc)
         * 
         * @see com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml.jackson.core.JsonParser,
         * com.fasterxml.jackson.databind.DeserializationContext)
         */
        @Override
        public List<String> deserialize(JsonParser parser, DeserializationContext context)
                throws IOException, JsonProcessingException {
            String value = parser.getValueAsString();
            List<String> result = new ArrayList<String>();
            if (StringUtils.isNoneEmpty(value)) {
                result = Arrays.asList(value.split(VERTICAL_DELIMITER)).stream().sorted()
                        .map(s -> (s.trim())).collect(Collectors.toList());
            }
            return result;
        }

    }
    
    public static class VerticalDelimiterSerializer extends JsonSerializer<List<String>> {

        /* (non-Javadoc)
         * @see com.fasterxml.jackson.databind.JsonSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider)
         */
        @Override
        public void serialize(List<String> value, JsonGenerator genertor, SerializerProvider serializers)
                throws IOException {
            String result = "";
            if(CollectionUtils.isNotEmpty(value)) {
                value.stream().sorted();
                result = String.join(VERTICAL_DELIMITER, value);
            }
            genertor.writeString(result);
        }
        
    }
}
